import {createRouter, createWebHashHistory} from 'vue-router';
import routes from 'virtual:generated-pages';
import util from '@/util/util';

export const VueRouter = createRouter({
  routes,
  history: createWebHashHistory()
});

export default {
  get param() {
    return util.getUrlParam();
  },

  get currentUrl() {
    return location.hash.split('?')[0].replace('#', '');
  },

  get currentRoute() {
    return VueRouter.currentRoute;
  },

  /**
   * 路由跳转
   * @param path 跳转的地址
   * @param param 跳转携带的参数
   * @param replace 是否替换当前路由栈
   */
  go(path, param, replace = false) {
    const urlParam = util.getUrlParam(path);
    const query = {
      ...urlParam,
      ...param
    };
    let url = path.split('?')[0];

    if (url.includes('http://') || url.includes('https://')) {
      const queryArr = [];
      Object.entries(query).forEach(([k, v]) => {
        queryArr.push(`${k}=${v}`);
      });
      url = `${url}?${queryArr.join('&')}`;
      if (!replace) {
        location.href = url;
      } else {
        location.replace(url);
      }
    } else {
      if (!replace) {
        VueRouter.push({ path: url, query });
      } else {
        VueRouter.replace({ path: url, query });
      }
    }
  },

  /**
   * 后退
   */
  back() {
    VueRouter.go(-1);
  },

  /**
   * 路由跳转,并替换当前路由
   * @param path 跳转的地址
   * @param param 跳转携带的参数
   */
  replace(path, param) {
    this.go(path, param, true);
  },
};
